package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.common.R;
import com.itheima.dao.CategoryDao;
import com.itheima.domain.Category;
import com.itheima.domain.Dish;
import com.itheima.domain.DishFlavor;
import com.itheima.dto.DishDto;
import com.itheima.service.DishFlovarService;
import com.itheima.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.awt.print.PrinterGraphics;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private CategoryDao categoryDao;
    @Autowired
    private DishFlovarService dishFlovarService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page<DishDto>> page(Integer page, Integer pageSize, String name) {
        //分页查询 dish表
        Page<Dish> ipage = new Page<>(page, pageSize);
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.orderByDesc(Dish::getCode).like(name != null, Dish::getName, name);
        dishService.page(ipage, lqw);

        // 把查询结果赋值给 dtopage 除了records属性，目的为了把 records<Dish> 转化为 records<DishDto>
        Page<DishDto> dtopage = new Page<>();
        BeanUtils.copyProperties(ipage, dtopage, "records");
        List<Dish> records = ipage.getRecords();

        //    把 records<Dish> 转化为 records<DishDto>
        List<DishDto> list = records.stream().map((item) -> {
            DishDto dto = new DishDto();
            BeanUtils.copyProperties(item, dto);
            Long categoryId = item.getCategoryId();

            //查询 category表
//            LambdaQueryWrapper<Category> lqw2 = new LambdaQueryWrapper<>();
//            lqw2.eq(Category::getId, categoryId);
            Category category = categoryDao.selectById(categoryId);
            log.info("category===>" + category);

            //给 categoryName 赋值
            dto.setCategoryName(category.getName());
            return dto;
        }).collect(Collectors.toList());

        dtopage.setRecords(list);
        return R.success(dtopage);

    }

    /**
     * 保存数据
     *
     * @param dishDto
     * @return
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        //删除缓存
        String key = "dish_" + dishDto.getCategoryId() + "_1" ;
        redisTemplate.delete(key);
        R r = dishService.saveWithFlovar(dishDto);
        return r;
    }

    /**
     * 查询菜品和口味
     *
     * @param id
     * @return
     */
    @GetMapping("{id}")
    public R<DishDto> get(@PathVariable Long id) {
        DishDto dishDto1 = dishService.getWithFlavor(id);
        return R.success(dishDto1);
    }

    /**
     * 修改菜品和口味
     *
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        //删除缓存
        String key = "dish_" + dishDto.getCategoryId() + "_1" ;
        redisTemplate.delete(key);
        R r = dishService.updateWithFlavor(dishDto);
        return r;
    }


    /**
     * 查询菜品
     *
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {
        //查询 redis数据库
        List<DishDto> Dtolist = null;
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
        Dtolist = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (Dtolist != null) {
            return R.success(Dtolist);
        }
        log.info("dish ===>{}", dish);
        LambdaQueryWrapper<Dish> lqw = new LambdaQueryWrapper<>();
        lqw.eq(dish.getCode() != null, Dish::getCode, 1)
                .eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        lqw.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);
        List<Dish> list = dishService.list(lqw);
        //遍历集合 进行相关操作
        Dtolist = list.stream().map((item -> {
            //创建 Dto 对象
            DishDto dishDto = new DishDto();
            // 赋值给 Dto
            BeanUtils.copyProperties(item, dishDto, "records");
            // 获取 DishId
            Long dishId = item.getId();
            // 根据条件查询 口味表
            LambdaQueryWrapper<DishFlavor> lqw2 = new LambdaQueryWrapper<>();
            lqw2.eq(DishFlavor::getDishId, dishId);
            List<DishFlavor> flavors = dishFlovarService.list(lqw2);
            // 把查询的口味信息 赋值给 Dto
            dishDto.setFlavors(flavors);
            return dishDto;
        })).collect(Collectors.toList());
        //把数据 添加道 redis 数据库中
        redisTemplate.opsForValue().set(key,Dtolist,60, TimeUnit.MINUTES);
        return R.success(Dtolist);
    }

    /**
     * 停售
     *
     * @param ids
     * @return
     */
    @PostMapping("/status/0")
    public R<String> ban(String ids) {
        Dish dish = new Dish();
        log.info("list=" + ids);
        String[] dishIds = ids.split(",");
        for (String id : dishIds) {
            long id1 = Long.parseLong(id);
            Dish result = dishService.getById(id1);
            BeanUtils.copyProperties(result, dish);
            dish.setStatus(0);
            dishService.updateById(dish);
        }
        return R.success("停售成功");
    }

    /**
     * 起售
     *
     * @param ids
     * @return
     */
    @PostMapping("/status/1")
    @Transactional
    public R<String> start(String ids) {
        //创建 dish 对象
        Dish dish = new Dish();
        log.info("list=" + ids);
        //获得 ids数组
        String[] dishIds = ids.split(",");
        for (String id : dishIds) {
            //转换类型
            long id1 = Long.parseLong(id);
            //查询菜单表
            Dish result = dishService.getById(id1);
            //赋值给 dish 对象
            BeanUtils.copyProperties(result, dish);
            //设置状态为 1
            dish.setStatus(1);
            //修改菜单表
            dishService.updateById(dish);
        }
        return R.success("起售成功");
    }

    /**
     * 删除菜品
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    @Transactional
    public R<String> delete(@RequestParam String ids) {
        //删除缓存
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        //获得 ids 数组
        String[] dishIds = ids.split(",");
        List<Long> list = new ArrayList<>();
        for (int i = 0; i < dishIds.length; i++) {
            //转换类型
            long dishId = Long.parseLong(dishIds[i]);
            //设置查询条件
            LambdaQueryWrapper<DishFlavor> lqw = new LambdaQueryWrapper<>();
            lqw.eq(DishFlavor::getDishId, dishId);
            List<DishFlavor> list1 = dishFlovarService.list(lqw);
            log.info("list1=" + list1);
            //获得 口味表的 id
            for (DishFlavor data : list1) {
                Long id = data.getId();
                //删除口味信息
                dishFlovarService.removeById(id);
            }
            //在菜单表中删除相关数据
            dishService.removeById(dishId);
        }
        return R.success("删除成功");
    }


}
